import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
import { Redis } from 'ioredis';

@Injectable()
export class WxredisService {
  public client: Redis;
  constructor(private readonly redisService: RedisService) {
    this.getClient();
  }

  async getClient() {
    this.client = await this.redisService.getClient();
    const listen = this.client.addListener('update-token', v => {
      // console.log('update-token', v);
    });
  }

  // 设置值的方法
  async set(key: string, value: any, seconds?: number) {
    value = JSON.stringify(value);
    if (!this.client) {
      await this.getClient();
    }
    if (!seconds) {
      await this.client.set(key, value);
    } else {
      await this.client.set(key, value, 'EX', seconds);
    }
  }

  // 获取值的方法
  async get<T>(key: string): Promise<T> {
    if (!this.client) {
      await this.getClient();
    }
    const data = await this.client.get(key);
    if (data == null || data == '') {
      return null;
    }
    return JSON.parse(data);
  }
}
